define(function (require, exports, module) {
    /**
     * 指标运算
     */
    var IndCalculate = function (grid,idenCountEle,calculateIden,validationOk,closeIndenCountDialog,callback) {
        this.callback=callback;
        this.grid = grid;
        // this.container=container;
        this.idenCountEle = idenCountEle;
        this.calculateIden=calculateIden;//指标运算,返回头部信息、运算类型、运算公式
        this.validationOk = validationOk;//验证公式通过
        this.closeIndenCountDialog = closeIndenCountDialog;
        this.selector = null;
        this.$control = null;

        this.preTab = 'quik';
        this.currentTab = 'quik';
        this.$quikContent = null;
        this.$userdefContent = null;
        this.$confirmContent = null;
        //grid的header数据集合
        this.gridHeaders = [];
        //是否已经初始化界面
        this.isInit = false;

        //当点击下一步时，该变量存放当前tab,为后续运算提供公式选择
        // this.waitCalTab = 'quik';

        //快速运算使用
        this.okValidation = false;
        this.calcFunc = "divth";
        this.calcTemplate = '';
        this.calcInds = [];
        this.funcTip = {
            // "yoyg": "[同比增长] : 后者比前者增加的数值. 此方法参数2个.",
            // "aver": "[平均值] : 几个指标的平均值. 此方法参数不限.",
            // "sum": "[累加和] : 几个指标的累加和. 此方法参数不限.",
            "divth": "[/千] : 用于 人→千人；元→千元. 此方法参数1个.",
            "multh": "[×千] : 用于 千人→人 ; 千元→元. 此方法参数1个."
        }

        //自定义运算使用
        this.okDefValidation = false;
        this.defFuncTemplate = [];
    }
    IndCalculate.prototype = {
        toggle: function () {
            this.create();
        },
        create: function () {
            if (!this.isInit) {
                var that = this;
                //快速运算内容---------------------------------------------------------------------------------------------------
                this.$quikContent = $('<div id="quik" class="show highlight-box-inner" style="background-color:#ffffff;font-size:0.8rem;padding-top:0.4rem">'
                + '<table width="100%">'
                + ' <tbody>'
                + '<tr style="height:2rem">'
                // + '<td colspan="2">点击选择指标项 :</td>'
                // + '<td style="text-align: center"><a id="all" href="javascript:void(0);"><span><b class="ui-icon ui-icon-play"></b>全选</span></a>'
                // + '<span>&nbsp;&nbsp;&nbsp;</span><a id="clear" href="javascript:void(0);"><span><b class="ui-icon ui-icon-play"></b>清空</span></a></td>'
                + '</tr>'
                + '  <tr>'
                + '  <td width="50%">'
                + ' <fieldset style="border:1px solid #FFFFFF" class="highlight-box" title="选择的指标列表,请从下方选择并进行操作">'
                + ' <legend class="title">'
                + '  选择指标'
                + ' </legend>'
                + '<div id="quikAllIndList" class="IDENList" style=" OVERFLOW-Y:auto;height:13rem">'
                + ' </div>'
                + '  </fieldset>'
                + ' </td>'
                // + ' <td width="33%">'
                // + ' <fieldset style="border:1px solid #FFFFFF" class="highlight-box" title="选择的指标列表,请从下方选择并进行操作">'
                // + '  <legend class="title">'
                // + '  已选指标'
                // + '  </legend>'
                // + ' <div id="selIndList" class="IDENList" style=" OVERFLOW-Y:auto;height:13rem">'
                // + '</div>'
                // + '</fieldset>'
                // + '</td>'
                + ' <td width="33%">'
                + ' <fieldset style="border:1px solid #FFFFFF" class="highlight-box" title="常用公式列表, 鼠标移动到相应项上时, 会在下方给出公式说明">'
                + '<legend class="title">'
                + ' 常用公式列表'
                + '</legend>'
                + '<div id="FunctionList" class="IDENList" style="font-size: 0.8rem;OVERFLOW-Y:auto;height:13rem">'
                + '<input type="radio" name="funcitem" value="divth" checked>/千<br>'
                + '<input type="radio" name="funcitem" value="multh">×千<br>'
                + '</div>'
                + '</fieldset>'
                + '</td>'
                + '</tr>'
                + '<tr>'
                + '<td colspan="2">'
                + '<span id="msg"></span>'
                + '</td>'
                + '<td style="text-align: center"><button id="quickNext">下一步</button>'
                + '</td>'
                + '</tr>'
                + '</tbody>'
                + '</table>'
                + '</div>');
                this.idenCountEle.quik.html(this.$quikContent)
                //自定义运算内容----------------------------------------------------------------------------------------------------
                this.$userdefContent = $('<div id="calculator-userDefined" class="hide" style="background-color:#ffffff;font-size:0.8rem"><br>'
                + '<table id="calculateFrame" border="0" cellpadding="2" cellspacing="2">'
                + '<tbody>'
                + '    <tr>'
                + '        <td colspan="2">'
                + '          <div id="LED" title="指标运算显示, 您所定义的运算公式" class="highlight-box-inner" style="text-align:right;OVERFLOW-Y:auto;height:3rem;border:1px solid #F5F5F5"></div>'
                + '      </td>'
                + '  </tr>'
                + '  <tr>'
                + '      <td>'
                + '          <fieldset style="border:1px solid #FFFFFF" class="highlight-box-inner" title="选择的指标列表,请从下方选择并进行操作">'
                + '              <legend class="title">'
                + '              指标列表'
                + '              </legend>'
                + '              <div id="userIndList" class="IDENList" style=" OVERFLOW-Y:auto;height:30rem;width:22rem">'
                + '              </div>'
                + '          </fieldset>'
                + '      </td>'
                + '      <td width="55%" style="padding: 0;float: left;margin-left: 20px;">'
                + '          <fieldset style="border:1px solid #FFFFFF" id="CalculateNotationFieldset" class="highlight-box-inner">'
                + '              <legend class="title">'
                + '              运算符'
                + '              </legend>'
                + '              <div id="btnContainer" title="运算符" class="IDENList" style="overflow: hidden;">'
                + '                  <div id="buttons" style="height:auto;width: 180px;">'
                + '                      <img id="bbks" value="Backspace" src="static/images/calculator/enable/b23.png" onmouseover="this.src=\'static/images/calculator/over/b23.png\'"  onmouseout="this.src=\'static/images/calculator/enable/b23.png\'"/>'
                + '                      <img id="bc" value="C" src="static/images/calculator/enable/b24.png" onmouseover="this.src=\'static/images/calculator/over/b24.png\'" onmouseout="this.src=\'static/images/calculator/enable/b24.png\'"/>'
                + '                          <img id="bcent" value="%" src="static/images/calculator/enable/b20.png" onmouseover="this.src=\'static/images/calculator/over/b20.png\'" onmouseout="this.src=\'static/images/calculator/enable/b20.png\'"/>'
                + '                          <img id="bl" value="(" src="static/images/calculator/enable/b15.png" onmouseover="this.src=\'static/images/calculator/over/b15.png\'" onmouseout="this.src=\'static/images/calculator/enable/b15.png\'" />'
                + '                          <img id="n7" value="7" src="static/images/calculator/enable/b7.png" onmouseover="this.src=\'static/images/calculator/over/b7.png\'" onmouseout="this.src=\'static/images/calculator/enable/b7.png\'"/>'
                + '                          <img id="n8" value="8" src="static/images/calculator/enable/b8.png" onmouseover="this.src=\'static/images/calculator/over/b8.png\'" onmouseout="this.src=\'static/images/calculator/enable/b8.png\'" />'
                + '                          <img id="n9" value="9" src="static/images/calculator/enable/b9.png" onmouseover="this.src=\'static/images/calculator/over/b9.png\'" onmouseout="this.src=\'static/images/calculator/enable/b9.png\'"/>'
                + '                          <img id="bdivision" value="/" src="static/images/calculator/enable/b14.png" onmouseover="this.src=\'static/images/calculator/over/b14.png\'" onmouseout="this.src=\'static/images/calculator/enable/b14.png\'"/>'
                + '                          <img id="br" value=")" src="static/images/calculator/enable/b16.png" onmouseover="this.src=\'static/images/calculator/over/b16.png\'" onmouseout="this.src=\'static/images/calculator/enable/b16.png\'"/>'
                + '                          <img id="n4" value="4" src="static/images/calculator/enable/b4.png" onmouseover="this.src=\'static/images/calculator/over/b4.png\'" onmouseout="this.src=\'static/images/calculator/enable/b4.png\'"/>'
                + '                          <img id="n5" value="5" src="static/images/calculator/enable/b5.png" onmouseover="this.src=\'static/images/calculator/over/b5.png\'" onmouseout="this.src=\'static/images/calculator/enable/b5.png\'"/>'
                + '                          <img id="n6" value="6"  src="static/images/calculator/enable/b6.png" onmouseover="this.src=\'static/images/calculator/over/b6.png\'" onmouseout="this.src=\'static/images/calculator/enable/b6.png\'"/>'
                + '                          <img id="bmultiply" value="*" src="static/images/calculator/enable/b13.png" onmouseover="this.src=\'static/images/calculator/over/b13.png\'" onmouseout="this.src=\'static/images/calculator/enable/b13.png\'"/>'
                + '                          <img id="bsqrt" value="sqrt" src="static/images/calculator/enable/b17.png" onmouseover="this.src=\'static/images/calculator/over/b17.png\'" onmouseout="this.src=\'static/images/calculator/enable/b17.png\'"/>'
                + '                          <img id="n1" value="1" src="static/images/calculator/enable/b1.png" onmouseover="this.src=\'static/images/calculator/over/b1.png\'" onmouseout="this.src=\'static/images/calculator/enable/b1.png\'"/>'
                + '                          <img id="n2" value="2" src="static/images/calculator/enable/b2.png" onmouseover="this.src=\'static/images/calculator/over/b2.png\'" onmouseout="this.src=\'static/images/calculator/enable/b2.png\'"/>'
                + '                          <img id="n3" value="3" src="static/images/calculator/enable/b3.png" onmouseover="this.src=\'static/images/calculator/over/b3.png\'" onmouseout="this.src=\'static/images/calculator/enable/b3.png\'"/>'
                + '                          <img id="bminus" value="-" src="static/images/calculator/enable/b12.png" onmouseover="this.src=\'static/images/calculator/over/b12.png\'" onmouseout="this.src=\'static/images/calculator/enable/b12.png\'"/>'
                + '                          <img id="bpower" value="x^n" src="static/images/calculator/enable/b18.png" onmouseover="this.src=\'static/images/calculator/over/b18.png\'" onmouseout="this.src=\'static/images/calculator/enable/b18.png\'"/>'
                + '                          <img id="n0" value="0" src="static/images/calculator/enable/b10.png" onmouseover="this.src=\'static/images/calculator/over/b10.png\'" onmouseout="this.src=\'static/images/calculator/enable/b10.png\'"/>'
                + '                          <img id="n00" value="00" src="static/images/calculator/enable/b22.png" onmouseover="this.src=\'static/images/calculator/over/b22.png\'" onmouseout="this.src=\'static/images/calculator/enable/b22.png\'"/>'
                + '                          <img id="bdot" value="." src="static/images/calculator/enable/b21.png" onmouseover="this.src=\'static/images/calculator/over/b21.png\'" onmouseout="this.src=\'static/images/calculator/enable/b21.png\'"/>'
                + '                          <img id="badd" value="+" src="static/images/calculator/enable/b11.png" onmouseover="this.src=\'static/images/calculator/over/b11.png\'" onmouseout="this.src=\'static/images/calculator/enable/b11.png\'"/>'
                + '                          <img id="bevolution" value="x^1/n" src="static/images/calculator/enable/b19.png" onmouseover="this.src=\'static/images/calculator/over/b19.png\'" onmouseout="this.src=\'static/images/calculator/enable/b19.png\'"/>'
                + '                          <div style="text-align: right;display:inline"><br><br><button id="calc-next" title="点击这里进入下一个命名指标的标签">下一步</button><br><br>'
                + '                             <span id="userMsg"></span> '
                + '                          </div>'
                + '                      </div>'
                + '                  </div>'
                + '              </fieldset>'
                + '  </td>'
                + '      </tr>'
                + '  </tbody>'
                + '  </table>'
                + '</div>');
                this.idenCountEle.userDefined.html(this.$userdefContent)
                //确认指标内容------------------------------------------------------------------------------------------------------
                this.$confirmContent = $('<div id="confirm" class="hide" style="background-color:#ffffff;font-size:0.8rem;"><br>'
                + '<div class="highlight-box-inner" style="padding:1rem;">'
                + ' <div class="title">自定义指标命名</div>'
                + ' <div class="description">请在这里填写定义指标的名称、指标单位，文本中不要包含引号。</div>'
                + ' </div><br>'
                + ' <div class="highlight-box" style="padding:1rem">'
                + ' <label class="title block">'
                + ' 指标名称：'
                + '    <input type="text" id="indName" class="highlight-box-inner" style="width: 23rem;">'
                + '    </label><br><br>'
                + '     <label class="title block">'
                + '   指标单位：'
                + '       <input type="text" id="indUnit" class="highlight-box-inner" style="width: 23rem;">'
                + '       </label><br><br>'
                + '       <input type="checkbox" id="remainopen" class="highlight-box-inner" checked />'
                + '     <label class="title block">'
                + '   保持窗口'
                + '       </label>'
                + '        <div class="button_light right" style="text-align:right;width:90%">'
                + '         <br><br><span id="calcMsg"></span><br><br>'
                + '           <a id="calculateButton"  class="ui item" href="javascript:void(0);">运 算</a>'
                + '        </div>'
                + '        <div class="clear"></div>'
                + '    </div>'
                + ' </div>');
                this.idenCountEle.confirm.html(this.$confirmContent)
                //------------------------------------------------------------------------------------------------------------------

                this.$control = $("#com-selection");
                //初始化各个Tab内容
                this.initTabContent();
                //添加事件
                this.addEvent();
                this.isInit = true;
            } else {
            }
        },
        distroy: function () {
            // this.$control = $("#com-selection");
            // this.$control.empty();
            // this.$control = null;
            this.isInit = false;
        },
        switchTab: function (tab) {
            this.$quikContent.removeClass("hide").addClass("show");
            this.$userdefContent.removeClass("show").addClass("hide");
            this.$confirmContent.removeClass("show").addClass("hide");
            switch (tab) {
                case 'quik':
                    this.$quikContent.removeClass("hide").addClass("show");
                    this.$userdefContent.removeClass("show").addClass("hide");
                    this.$confirmContent.removeClass("show").addClass("hide");
                    break;
                case 'userdef':
                    this.$quikContent.removeClass("show").addClass("hide");
                    this.$userdefContent.removeClass("hide").addClass("show");
                    this.$confirmContent.removeClass("show").addClass("hide");
                    break;
                case 'confirm':
                    if (this.preTab == 'quik') {
                        this.quikValidate();
                        //alert(this.okValidation);
                        if (this.okValidation) {
                            this.$quikContent.removeClass("show").addClass("hide");
                            this.$userdefContent.removeClass("show").addClass("hide");
                            this.$confirmContent.removeClass("hide").addClass("show");
                        } else {
                            $("#com-tab a[data-value='quik']").siblings().removeClass("active");
                            $("#com-tab a[data-value='quik']").addClass("active");
                            this.currentTab = 'quik';
                            this.$quikContent.removeClass("hide").addClass("show");
                            this.$userdefContent.removeClass("show").addClass("hide");
                            this.$confirmContent.removeClass("show").addClass("hide");
                        }
                    }
                    if (this.preTab == 'userdef') {
                        this.defValidate();
                        if (this.okDefValidation) {
                            this.$quikContent.removeClass("show").addClass("hide");
                            this.$userdefContent.removeClass("show").addClass("hide");
                            this.$confirmContent.removeClass("hide").addClass("show");
                        } else {
                            $("#com-tab a[data-value='userdef']").siblings().removeClass("active");
                            $("#com-tab a[data-value='userdef']").addClass("active");
                            this.currentTab = 'userdef';
                            this.$quikContent.removeClass("show").addClass("hide");
                            this.$userdefContent.removeClass("hide").addClass("show");
                            this.$confirmContent.removeClass("show").addClass("hide");
                        }
                    }
                    break;
                default:
                    break;
            }
        },
        initTabContent: function () {
            /**
             * 主要是快速、自定义初始化指标列表
             */
            //获取grid表头label数据
            for (var i = 0; i < this.grid.columnCount; i++) {
                var headJson = {};
                headJson.name = this.grid.getColLabel[i].idenName;
                headJson.columnIndex = i;
                this.gridHeaders.push(headJson);
            }
            /**
             *初始化界面
             * 1、待选指标、已选指标
             * 2、常用公式列表
             */
            //1
            var cbs = $("#" + this.container + " .calculate");
            var splitNum=this.grid.columnCount;
            for (var j = 0; j < this.grid.numIden.length; j++) {
                var indexSplit = this.grid.numIden[j].idenName.indexOf("）");
                var splitStr = this.grid.numIden[j].idenName;
             
                // var $div = $("<div>").css({
                //     "margin-top": "0.4rem",
                //     "display": "block",
                //     "font-size": "0.8rem",
                //     "border": "1px solid #F5F5F5"
                // }).attr("data-value", j).attr("id",j).attr("idenCode",this.grid.numIden[j].idenCode).addClass("indItem").html(splitStr);
                // $div.hover(function () {
                //     $(this).css({
                //         "background-color": "#D1EEEE"
                //     });
                // });
                // $div.mouseout(function () {
                //     $(this).css({
                //         "background-color": "#ffffff"
                //     });
                // });

                var radiobtn = '<input type="radio" name="quikAllIndList" value="'+this.grid.numIden[j].idenCode+'">'+splitStr+'</br>';


                $("#quikAllIndList").append(radiobtn);
                //---------------------------------
                var $div2 = $("<div>").css({
                    "margin-top": "0.4rem",
                    "display": "block",
                    "font-size": "0.8rem",
                    "border": "1px solid #F5F5F5"
                }).attr("data-value", j).attr("idenCode",this.grid.numIden[j].idenCode).addClass("userIndItem").html(splitStr);
                $div2.hover(function () {
                    $(this).css({
                        "background-color": "#D1EEEE"
                    });
                });
                $div2.mouseout(function () {
                    $(this).css({
                        "background-color": "#ffffff"
                    });
                });
                $("#userIndList").append($div2);
            }
        },
        addEvent: function () {
            var that = this;
            $("i.remove").click(function () {
                that.distroy();
            });
            $(".item", "#com-tab").click(function () {
                if (that.currentTab === $(this).attr("data-value")) {
                    return;
                }
                $(this).addClass("active").siblings().removeClass("active");
                that.preTab = that.currentTab;
                that.currentTab = $(this).attr("data-value");
                that.switchTab(that.currentTab);
            });

            $("#quikAllIndList .indItem").each(function () {
                        $(this).click(function () {
                            if($("#selIndList").find("#"+$(this).attr("id")+"0").length==0) {
                                var $this = $(this);
                                var $div = $("<div>").css({
                                    "margin-top": "0.4rem",
                                    "display": "block",
                                    "font-size": "0.8rem",
                                    "border": "1px solid #F5F5F5"
                                }).attr("data-value", $this.attr("data-value")).attr("idenCode", $this.attr("idenCode")).attr("id", $this.attr("id") + "0").addClass("indItem").html($this.html());
                                $div.hover(function () {
                                    $(this).css({
                                        "background-color": "#D1EEEE"
                                    });
                                });
                                $div.mouseout(function () {
                                    $(this).css({
                                        "background-color": "#ffffff"
                                    });
                                });
                                $("#com-selection #selIndList").append($div);
                            }
                        });
            });
            $("#selIndList").click(function (e) {
                if ($(e.target).hasClass("indItem")) {
                    $(e.target).remove();
                }
            });
            $("#com-selection #all").click(function () {
                $("#quikAllIndList .indItem").each(function () {
                    var $this=$(this);
                    if($("#selIndList").find("#"+$this.attr("id")+"0").length==0) {
                        $this.trigger("click");
                    }
                });
            });
            $("#com-selection #clear").click(function () {
                $("#selIndList .indItem").each(function () {
                    $("#selIndList").empty();
                });
            });
            /**
             * 添加到计算公式容器中，并放入堆栈中
             */
            $("#com-selection .userIndItem").each(function () {
                $(this).click(function () {
                    var $this = $(this);
                    var $div = $("<div>").css({
                        "margin-top": "0.4rem",
                        "display": "block",
                        "font-size": "0.8rem",
                        "border": "1px solid #F5F5F5",
                        "width": "12rem"
                    }).attr("data-value", $this.attr("data-value")).attr("idencode", $this.attr("idencode")).addClass("userIndItem").html($this.html());
                    $div.css({
                        "display": "inline"
                    });
                    that.pushDefFuncTemplate($div);
                    //指标
                    //document.getElementById("n0").disabled = "disabled";
                });
            });
            $(this).find("*").each(function () {
                $(this).addClass("disabled");
                $(this).attr("disabled", "disabled");
            });
            $("input[name='funcitem']").each(function () {
                $(this).hover(function () {
                    var value = $(this).attr("value");
                    var tip = '';
                    switch (value) {
                        case 'yoyg':
                            tip = that.funcTip.yoyg;
                            break;
                        case 'aver':
                            tip = that.funcTip.aver;
                            break;
                        case 'sum':
                            tip = that.funcTip.sum;
                            break;
                        case 'divth':
                            tip = that.funcTip.divth;
                            break;
                        case 'multh':
                            tip = that.funcTip.multh;
                            break;
                        default:
                            break;
                    }
                    $("#com-selection #msg").text(tip);
                });
            });
            $("#com-selection #quickNext").click(function () {
                that.quikValidate();
            });

            $("#com-selection #calculateButton").click(function () {
                that.returnCalFormula();
                var val = $("#com-selection #remainopen").prop("checked");
                var msg = $("#com-selection #calcMsg").text();
                if (!val && msg == '') {
                    that.distroy();
                    that.closeIndenCountDialog();
                }
            });

            //自定义运算界面事件注册
            $("#bbks").click(function () {
                that.popDefFuncTemplate();
            });
            $("#bc").click(function () {
                that.clearDefFuncTemplate();
            });
            $("#bcent").click(function () {
                that.pushDefFuncTemplate("%");
            });
            $("#bl").click(function () {
                that.pushDefFuncTemplate("(");
            });
            for (var n = 0; n <= 9; n++) {
                $("#n" + n).click(function () {
                    that.pushDefFuncTemplate($(this).attr("id").substring(1));
                });
            }
            $("#n00").click(function () {
                that.pushDefFuncTemplate("00");
            });
            $("#bdivision").click(function () {
                that.pushDefFuncTemplate("/");
            });
            $("#br").click(function () {
                that.pushDefFuncTemplate(")");
            });
            $("#bmultiply").click(function () {
                that.pushDefFuncTemplate("*");
            });
            $("#bsqrt").click(function () {
                that.pushDefFuncTemplate("sqrt");
            });
            $("#bminus").click(function () {
                that.pushDefFuncTemplate("-");
            });
            $("#bpower").click(function () {
                that.pushDefFuncTemplate("^");
            });
            $("#bdot").click(function () {
                that.pushDefFuncTemplate(".");
            });
            $("#badd").click(function () {
                that.pushDefFuncTemplate("+")
            });
            $("#bevolution").click(function () {
                that.pushDefFuncTemplate("^1/")
            });
            $("#calc-next").click(function () {
                that.defValidate();
            });

        },
        //快速运算验证
        quikValidate: function () {
            var that = this;
            var indName = '';
            var indUnit = '';
            var failureMsg = '';
            that.okValidation = true;
            //判断已选指标是否符合运算公式,主要判断个数
            // var length = $("#com-selection #selIndList").find(".indItem").length;
            var length = $("input[name='quikAllIndList']:checked").val();
            var value = $("input[name='funcitem']:checked").val();
            switch (value) {
                // case 'yoyg':
                //     indName = '同比增长';
                //     indUnit = '%';
                //     if (length != 2) {
                //         that.okValidation = false;
                //         failureMsg = that.funcTip.yoyg;
                //     }
                //     break;
                // case 'aver':
                //     indName = '平均值';
                //     indUnit = '单位';
                //     if (length == 0) {
                //         that.okValidation = false;
                //         failureMsg = that.funcTip.aver;
                //     }
                //     break;
                // case 'sum':
                //     indName = '累加和';
                //     indUnit = '单位';
                //     if (length == 0) {
                //         that.okValidation = false;
                //         failureMsg = that.funcTip.sum;
                //     }
                //     break;
                case 'divth':
                    indName = '/千';
                    indUnit = '单位';
                    if (!length) {
                        that.okValidation = false;
                        failureMsg = that.funcTip.divth;
                    }
                    break;
                case 'multh':
                    indName = '×千';
                    indUnit = '单位';
                    if (!length) {
                        that.okValidation = false;
                        failureMsg = that.funcTip.multh;
                    }
                    break;
                default:
                    break;
            }
            if (that.okValidation) {
                that.calcFunc = value;
               
                //清空已选指标数组
                that.calcInds.length = 0;
                $("#com-selection #selIndList").find(".indItem").each(function () {
                    that.calcInds.push($(this));
                });
                //填充确定指标名称和单位
                $("#com-selection #indName").val(indName);
                $("#com-selection #indUnit").val(indUnit);
                //生成公式模板
                that.quikFuncTemplate();
                $("#com-selection #msg").text("");
                that.preTab = 'quik';
                $(".item:last", "#com-tab").trigger("click");
                that.validationOk();
            } else {
                $("#com-selection #msg").text(failureMsg);
            }
        },
        //自定义运算验证
        defValidate: function () {
            var that = this;
            if (that.defFuncTemplate.length == 0) {
                that.okDefValidation = false;
                $("#userMsg").text("自定义公式不能为空，请重新定义.")
                return;
            } else {
                var exeStr = '';
                var copyTemplate = that.defFuncTemplate.slice();
                var leng = copyTemplate.length;
                for (var i = 0; i < leng; i++) {
                    if (typeof copyTemplate[i] == 'object') {
                        copyTemplate[i] = 0;
                    }
                    exeStr = exeStr + copyTemplate[i];
                }
                try {
                    $("#userMsg").text("");
                    // let rel = eval("'"+exeStr+"'");
                    let rel = eval(exeStr)
                    rel = rel.toFixed(2);
                    that.preTab = 'userdef';
                    that.okDefValidation = true;
                    
                    $(".item:last", "#com-tab").trigger("click");

                    that.validationOk();
                    return;
                } catch (e) {
                    that.okDefValidation = false;
                    $("#userMsg").text("自定义公式错误，请重新定义.")
                    return;
                }
            }
        },
        //返回运算信息及公式
        returnCalFormula:function(){
            if (this.preTab == 'quik') {
                if (this.okValidation) {
                    var $confirmName = $("#com-selection #indName").val();
                    var $confirmUnit = $("#com-selection #indUnit").val();
                    if ($confirmName == '' || $confirmUnit == '') {
                        $("#com-selection #calcMsg").text("请输入新指标名称和单位，同时不要包含引号等特殊字符.");
                        return;
                    }
   
                    var tempCalcTemplate = this.calcTemplate;
                    var ran = Math.floor((Math.random()*1000)+1);//介于 1 到 1000 之间的一个随机数
                    let idenCode='AAA'+ran;
                    let obj = {
                        headerData:{
                            idenCode:idenCode,
                            idenName:$confirmName,
                            unit: $confirmUnit,
                            idenType:2,
                            isIndCalculate:true//添加指标运算标识
                        },
                        formula:{
                            type:"quik",
                            idenCode:idenCode,
                            tempCalcTemplate:this.calcTemplate
                        }
                    }
                    this.calculateIden(obj)
                } else {
                    $("#com-selection #calcMsg").text("指标运算公式验证失败。");
                }
            }else if (this.preTab == 'userdef') {
                if (this.okDefValidation) {
                    var $confirmName = $("#com-selection #indName").val();
                    var $confirmUnit = $("#com-selection #indUnit").val();
                    if ($confirmName == '' || $confirmUnit == '') {
                        $("#com-selection #calcMsg").text("请输入新指标名称和单位，同时不要包含引号等特殊字符.");
                        return;
                    }
                    var copyTemplate = this.defFuncTemplate.slice();
                    var evalStr = [];
                    var len = copyTemplate.length;
                    let calcTemplate = {
                        numIden:[],
                        calcTemplate:""
                    }
                    for (var i = 0; i < len; i++) {
                        var item = copyTemplate[i];
                        if (typeof item == 'object') {
                            var column = item.attr("idencode");
                            calcTemplate.numIden.push(column)
                            evalStr = evalStr + column;
                        } else {
                            evalStr = evalStr + item;
                        }
                    }
                    calcTemplate.calcTemplate=evalStr;
                    var ran = Math.floor((Math.random()*1000)+1);//介于 1 到 1000 之间的一个随机数
                    let idenCode='AAA'+ran;
                    let obj = {
                        headerData:{
                            idenCode:idenCode,
                            idenName:$confirmName,
                            unit: $confirmUnit,
                            idenType:2//数字指标
                        },
                        formula:{
                            type:"userdef",
                            idenCode:idenCode,
                            tempCalcTemplate:calcTemplate
                        }
                    }
                    this.calculateIden(obj)
                 
                } else {
                    $("#com-selection #calcMsg").text("指标运算公式验证失败.");
                }
            }
        },
        //开始运算
        startCalculate: function (tableData,formula) {
            $("#com-selection #calcMsg").text("");
            let result;
            for(let i in formula){
                if(formula[i].type == "quik"){//快速运算
                    try {
                        let formulaObj = formula[i];
                        let template = formulaObj.tempCalcTemplate.calcTemplate;
                        for(let j in tableData){
                            var value = tableData[j][formulaObj.tempCalcTemplate.numIden];
                            var rel = 0;
                            if (value == null || value == ''|| value == '-') {
                                value = '-';
                                rel = '-';
                            }else{
                                var column = formulaObj.tempCalcTemplate.numIden;
                                let tempCalcTemplate = template.replace("{{" + column + "}}", value);
                                rel = eval(tempCalcTemplate);
                                rel = rel.toFixed(2);
                            }
                            tableData[j][formulaObj.idenCode] = rel;
                        }
                        result = tableData;
                    } catch (error) {
                        $("#com-selection #calcMsg").text("指标公式验证错误.");
                        result = false; 
                    }
                }else if(formula[i].type == "userdef"){//用户自定义
                    try {
                        let formulaObj = formula[i];
                        let template = formulaObj.tempCalcTemplate.calcTemplate;
                        let numIden = formulaObj.tempCalcTemplate.numIden;
                        for(let j in tableData){
                            var rel = 0;
                            let tempCalcTemplate =template;
                            for(let k in numIden){
                                let idenCode = numIden[k];
                                var value = tableData[j][idenCode];
                                if (value == null || value == ''|| value == '-') {
                                    value =0;
                                }
                                tempCalcTemplate = tempCalcTemplate.replace(idenCode, value);
                            }
                            rel = eval(tempCalcTemplate);
                            rel = rel.toFixed(2);
                            if(rel=="NaN"){//非数字值
                                tableData[j][formulaObj.idenCode] = "-";
                            }else{
                                tableData[j][formulaObj.idenCode] = rel;
                            }
                        }
                        result = tableData;
                    } catch (error) {
                        $("#com-selection #calcMsg").text("指标公式验证错误.");
                        result = false; 
                    }
                }
            }
            return result;
            
        },
        quikFuncTemplate: function () {
            var that = this;
            var value = that.calcFunc;
            switch (value) {
                // case 'yoyg':
                //     var column2 = that.calcInds[1].attr("data-value");
                //     var column1 = that.calcInds[0].attr("data-value");
                //     that.calcTemplate = '(parseFloat({{' + column2 + '}})-parseFloat({{' + column1 + '}}))/parseFloat({{' + column1 + '}})*100';
                //     // alert("计算公式" + that.calcTemplate);
                //     break;
                // case 'aver':
                //     that.calcTemplate = '(';
                //     var leng = that.calcInds.length;
                //     for (var i = 0; i < leng; i++) {
                //         var column = that.calcInds[i].attr("data-value");
                //         that.calcTemplate = that.calcTemplate + 'parseFloat({{' + column + '}})';
                //         if (i != that.calcInds.length - 1) {
                //             that.calcTemplate = that.calcTemplate + '+';
                //         }
                //     }
                //     that.calcTemplate = that.calcTemplate + ')/' + that.calcInds.length;
                //     break;
                // case 'sum':
                //     that.calcTemplate = '(';
                //     var leng = that.calcInds.length;
                //     for (var i = 0; i < leng; i++) {
                //         var column = that.calcInds[i].attr("data-value");
                //         that.calcTemplate = that.calcTemplate + 'parseFloat({{' + column + '}})';
                //         if (i != that.calcInds.length - 1) {
                //             that.calcTemplate = that.calcTemplate + '+';
                //         }
                //     }
                //     that.calcTemplate = that.calcTemplate + ')';
                //     break;
                case 'divth':
                    // var column = that.calcInds[0].attr("idencode");
                    var column = $("input[name='quikAllIndList']:checked").val();
                    that.calcTemplate = {
                        numIden:column,
                        calcTemplate:"parseFloat({{" + column + "}})/1000"
                    }
                    break;
                case 'multh':
                    // var column = that.calcInds[0].attr("idencode");
                    var column = $("input[name='quikAllIndList']:checked").val();
                    that.calcTemplate = {
                        numIden:column,
                        calcTemplate:"parseFloat({{" + column + "}})*1000"
                    }
                    break;
                default:
                    break;
            }
        },
        pushDefFuncTemplate: function (ind) {
            if (ind == 'sqrt') {
                //模板公式中pop中最后一项，添加sqrt(pop()),删除LED容器内的元素
                var lastObj = this.getDefFuncTemplate();
                if(!lastObj||lastObj=='undefined'){
                    $("#userMsg").text("sqrt运算符必须提供参数.");
                }else {
                    if (typeof lastObj == 'object') {
                        ind = $("<div></div>").css({
                            "border": "1px solid #F5F5F5",
                            "display": "block",
                            "width": "2rem",
                            "text-align": "center",
                            "display": "inline"
                        }).html("sqrt(" + lastObj.html() + ")").attr("data-value", lastObj.attr("data-value"));
                    } else {
                        ind = "Math.sqrt(" + lastObj + ")";
                    }
                    this.popDefFuncTemplate();
                }
            }
            this.defFuncTemplate.push(ind);
            if (typeof ind == 'string') {
                var $div = $("<div></div>").css({
                    "border": "1px solid #F5F5F5",
                    "display": "block",
                    "width": "2rem",
                    "text-align": "center",
                    "display": "inline"
                }).html(ind).attr("value", ind);
                $("#LED").append($div);
            } else {
                $("#LED").append(ind);
            }
            //控制界面可用性
        },
        popDefFuncTemplate: function () {
            var ind = this.defFuncTemplate.pop();
            if (typeof ind == 'string') {
                $("#LED").find("div:last").remove();
            } else {
                $("#LED").find(ind).remove();
            }
        },
        getDefFuncTemplate: function (index) {
            //if index=null,then pop last.
            if (!index||index=='undefined') {
                //alert(this.defFuncTemplate.pop());
                return this.defFuncTemplate[this.defFuncTemplate.length-1];
            }
            else if (this.defFuncTemplate.length > 0) {
                return this.defFuncTemplate[index];
            } else {
                return '';
            }
        },
        clearDefFuncTemplate: function () {
            this.defFuncTemplate.length = 0;
            $("#LED").empty();
        }
    };


    return {
        IndCalculate: IndCalculate
    }
    
});